<template>
  <div class="app-container">
    <el-form
      :inline="true"
    >
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="showAdd()"
        >{{ $t('add') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="list"
      style="width: 100%;"
    >
      <el-table-column :label="$t('name')" prop="roleName"/>
      <el-table-column :label="$t('keyName')" prop="roleCode"/>
      <el-table-column :label="$t('remark')" prop="roleDesc"/>
      <el-table-column :label="$t('time')" sortable width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span style="margin-left: 13px">{{ formatDate(scope.row.createdDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" :label="$t('function')">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >{{ $t('delete') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="handlePermission(scope.row)"
          >{{ $t('permission') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:right;margin: 15px 0">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :visible.sync="dialogPermissionVisible"
      :title="$t('permission')"
    >
      <div class="dialog-main-tree">
        <el-tree
          ref="menuTree"
          :data="treeData"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          node-key="id"
          highlight-current
          show-checkbox
          default-expand-all
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ getTitle(data.title) }}</span>
          </span>
        </el-tree>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="updatePermession()"
        >{{ $t('update') }}
        </el-button>
        <el-button
          type="default"
          @click="dialogPermissionVisible = false"
        >{{ $t('cancel') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogRoleVisible"
      :title="$t('permission')"
    >
      <el-form ref="iotRole" :model="form" label-width="80px">
        <el-form-item :label="$t('name')">
          <el-input v-model="iotRole.roleName"/>
        </el-form-item>
        <el-form-item :label="$t('keyName')">
          <el-input v-model="iotRole.roleCode"/>
        </el-form-item>
        <el-form-item :label="$t('remark')">
          <el-input v-model="iotRole.roleDesc"/>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="insertOrUpdateRole()"
        >{{ $t('update') }}
        </el-button>
        <el-button
          type="default"
          @click="dialogRoleVisible = false"
        >{{ $t('cancel') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  deleteCompanyRole,
  insertCompanyRole,
  pageGetCompanyRole,
  setMenuCompanyRole,
  updateCompanyRole
} from '@/api/iot/iotCompanyRoleApi'
import { numTreeCompanyMenu, treeCompanyMenu } from '@/api/iot/iotCompanyMenuApi'
import { getCompanyId, getPageSize, getShortCompanyName, setPageSize } from '@/util/storage'
import { formatDate, successNotice } from '@/util/common'

export default {
  name: 'CompanyRole',
  data() {
    return {
      treeData: [],
      menuIds: '',
      list: [],
      iotRole: {},
      dialogPermissionVisible: false,
      dialogRoleVisible: false,
      companyId: null,
      currentPage: 1,
      total: 0,
      pageSize: getPageSize()
    }
  },
  created() {
    const param = this.$route.query
    if (param != null && param.companyId) {
      this.companyId = param.companyId
      this.companyName = param.companyName
    } else {
      this.companyId = getCompanyId()
      this.companyName = getShortCompanyName()
    }
    this.setTagsViewTitle()
    this.pageGetCompanyRole()
  },
  methods: {
    getTitle(title) {
      if (!title) {
        return ''
      }
      let str = ''
      title.split(' ').forEach(s => {
        str = str + this.$t(s)
      })
      return str
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    handleSizeChange(val) {
      this.pageSize = val
      setPageSize(this.pageSize)
      this.pageGetDeviceStatus()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.pageGetCompanyRole()
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.companyName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    pageGetCompanyRole() {
      pageGetCompanyRole({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        companyId: this.companyId
      }).then(res => {
        const { data } = res
        this.list = data.data
        this.total = data.total
      })
    },
    handleUpdate(row) {
      this.iotRole = row
      this.dialogRoleVisible = true
    },
    numTreeCompanyMenu() {
      numTreeCompanyMenu({
        roleId: this.iotRole.roleId
      }).then(res => {
        const { data } = res
        this.checkedKeys = data
        return treeCompanyMenu({})
      })
        .then(res => {
          const { data } = res
          this.treeData = data
          // 解析出所有的太监节点
          this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeys, [])
          this.dialogPermissionVisible = true
        })
    },
    handlePermission(row) {
      this.iotRole = row
      this.numTreeCompanyMenu()
    },
    /**
     * 解析出所有的太监节点id
     * @param json 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(json, idArr, temp) {
      for (let i = 0; i < json.length; i++) {
        const item = json[i]
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp)
        } else {
          temp.push(idArr.filter(id => id === item.id))
        }
      }
      return temp
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getNodeData(data, done) {
      done()
    },
    handleDelete(row) {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(function() {
        return deleteCompanyRole({ 'roleId': row.roleId })
      }).then(() => {
        this.pageGetCompanyRole(that.page)
        successNotice(that)
      })
    },
    showAdd() {
      this.iotRole = {
        companyId: this.companyId
      }
      this.dialogRoleVisible = true
    },
    insertOrUpdateRole() {
      let res
      if (this.iotRole.roleId) {
        res = updateCompanyRole(
          {
            ...this.iotRole
          })
      } else {
        res = insertCompanyRole(
          {
            ...this.iotRole,
            companyId: this.companyId
          })
      }
      res.then(() => {
        this.dialogRoleVisible = false
        this.pageGetCompanyRole()
      })
    },
    updatePermession() {
      this.menuIds = ''
      this.menuIds = this.$refs.menuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.menuTree.getHalfCheckedKeys().join(','))
      setMenuCompanyRole({
        roleId: this.iotRole.roleId,
        menuIds: this.menuIds
      }).then(() => {
        this.dialogPermissionVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  .el-dialog {
    width: 61% !important;

    .dialog-main-tree {
      max-height: 400px;
      overflow-y: auto;
    }
  }

  .el-form-item__label {
    width: 20% !important;
    padding-right: 20px;
  }

  .el-form-item__content {
    margin-left: 20% !important;
  }
}
</style>
